package cn.conac.as.monitor.entity.weixin;

import java.io.IOException;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import cn.conac.as.framework.utils.FastJsonUtil;
import cn.conac.as.monitor.constant.WeixinFinalValueType;

/**
 * Created by liuwei on 2017-7-12.
 */
public class MessageKit
{
    public static String postTemplateMsg(WxinTemplate tm){
        CloseableHttpClient client =null;
        CloseableHttpResponse resp = null;
        try {
            client= HttpClients.createDefault();
            String url = WeixinFinalValueType.SEND_TEMPLATE_MSG;
            url = url.replace("ACCESS_TOKEN", RefreshAccessTokenTask.at);
            HttpPost post = new HttpPost(url);
            String json = FastJsonUtil.getJson(tm);
            post.addHeader("Content-type","application/json");

            StringEntity entity = new StringEntity(json, ContentType.create("application/json","UTF-8"));
            post.setEntity(entity);
            resp = client.execute(post);
            int statusCode = resp.getStatusLine().getStatusCode();
            if(statusCode >=200 && statusCode<300){
                String str = EntityUtils.toString(resp.getEntity());
                System.out.println(str);
                return str;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(client!=null) client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if(resp!=null) resp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
